<!--
* 方法:Role-info.vue
* 描述:角色权限添加/编辑组件
* 作者:Jimmy
* 日期:2018-08-07
*/
-->
<style lang="less">
  @import '../../../styles/common.less';
  @import '../system.less';
</style>
<template>
  <Card class="demo-spin-article">
    <p slot="title">
      {{data.label}}权限
    </p>
    <Row class="margin-bottom-15">
      <Button @click="$emit('toggle',{type:'list'})"><Icon type="ios-undo-outline" />
        返回
      </Button>
    </Row>
    <Row>
      <template>
        <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" :label-width="60">
          <FormItem label="角色名称" prop="name">
            <Input type="text" v-model="formCustom.name" :disabled="name_e"></Input>
          </FormItem>
          <FormItem label="是否启用" prop="isenable">
            <RadioGroup v-model="formCustom.isenable" type="button">
              <Radio v-for="item in isenablelist" :label="parseInt(item.value)" :key="item.id">{{item.name}}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="权限栏目">
            <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
              <Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="handleCheckAll">全选</Checkbox>
              <Button size="small" type="primary" @click="getRolePower()">添加栏目</Button>
            </div>
            <CheckboxGroup prop="powerid" v-model="formCustom.powerid" @on-change="checkAllGroupChange" class="cursor">
              <div v-for="item in powerData" :key="item.id">
                <Checkbox :label="item.id"><span>{{item.name}}</span><span v-if="item.isshow==2" style="margin-left: 3px;color: #f30;">隐</span></Checkbox>
                <Icon type="md-create" @click.native="getRolePower(item.id)"/>
                <Icon type="md-trash" v-if="item.children.length<=0" @click.native="delRolePower(item)"/>
                <div v-for="items in item.children" :key="items.id" class="padding-left-20">
                  <Checkbox :label="items.id"><span>{{items.name}}</span><span v-if="items.isshow==2" style="margin-left: 3px;color: #f30;">隐</span></Checkbox>
                  <Icon type="md-create" @click.native="getRolePower(items.id)"/>
                  <Icon type="md-trash" v-if="items.children.length<=0" @click.native="delRolePower(items)"/>
                  <div v-for="itemss in items.children" :key="itemss.id" class="padding-left-20">
                    <Checkbox :label="itemss.id"><span>{{itemss.name}}</span><span v-if="itemss.isshow==2" style="margin-left: 3px;color: #f30;">隐</span></Checkbox>
                    <Icon type="md-create" @click.native="getRolePower(itemss.id)"/>
                    <Icon type="md-trash" v-if="itemss.children.length<=0" @click.native="delRolePower(itemss)"/>
                    <div v-for="itemsss in itemss.children" :key="itemsss.id" class="padding-left-20">
                      <Checkbox :label="itemsss.id"><span>{{itemsss.name}}</span><span v-if="itemsss.isshow==2" style="margin-left: 3px;color: #f30;">隐</span></Checkbox>
                      <Icon type="md-create" @click.native="getRolePower(itemsss.id)"/>
                      <Icon type="md-trash" @click.native="delRolePower(itemsss)"/>
                    </div>
                  </div>
                </div>
              </div>
            </CheckboxGroup>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSubmit('formCustom')" :loading="formSave">
              <span v-if="!formSave">保存</span><span v-else>保存中</span>
            </Button>
            <Button @click="handleReset('formCustom')" class="margin-left-8">重置</Button>
          </FormItem>
        </Form>
      </template>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </Row>
    <Row>
      <template>
        <Modal v-model="powerModel" :title="powerTitle ? '添加栏目': '编辑栏目'" footer-hide>
          <Form ref="formCustomPower" :model="formCustomPower" :rules="ruleCustomPower" :label-width="60">
            <FormItem label="栏目" prop="pid">
              <Select v-model="formCustomPower.pid">
                <Option :value="0">一级栏目</Option>
                <template v-for="item in poweridlist">
                  <Option :key="item.id" :value="item.id">{{item.name}}</Option>
                  <template v-for="items in item.children">
                    <Option :value="items.id" :key="items.id" style="padding-left: 18px;">---{{items.name}}</Option>
                    <template v-for="itemss in items.children">
                      <Option :value="itemss.id" :key="itemss.id" style="padding-left: 32px;">---{{itemss.name}}</Option>
                      <template v-for="itemsss in itemss.children">
                        <Option :value="itemsss.id" :key="itemsss.id" disabled style="padding-left: 46px;">---{{itemsss.name}}</Option>
                      </template>
                    </template>
                  </template>
                </template>
              </Select>
            </FormItem>
            <FormItem label="名称" prop="name">
              <Input type="text" v-model="formCustomPower.name"></Input>
            </FormItem>
            <FormItem label="控制" prop="control">
              <Input type="text" v-model="formCustomPower.control"></Input>
            </FormItem>
            <FormItem label="方法" prop="action">
              <Input type="text" v-model="formCustomPower.action"></Input>
            </FormItem>
            <FormItem label="权限" prop="access">
              <Input type="text" v-model="formCustomPower.access"></Input>
            </FormItem>
            <FormItem label="排序" prop="sort">
              <Input type="text" v-model="formCustomPower.sort"></Input>
            </FormItem>
            <FormItem label="是否" prop="isshow">
              <RadioGroup v-model="formCustomPower.isshow" type="button">
                <Radio v-for="item in isshowlist" :label="parseInt(item.value)" :key="item.id">{{item.name}}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="saveRolePower('formCustomPower')" :loading="formSave">
                <span v-if="!formSave">保存</span><span v-else>保存中</span>
              </Button>
            </FormItem>
          </Form>
        </Modal>
      </template>
    </Row>
  </Card>
</template>
<script>
import bus from '@/libs/http/eventBus.js'
export default {
  props: ['data'],
  data () {
    // 添加和编辑权限开始
    const validateName = (rule, value, callback) => {
      if (!value && this.formType === 'add') {
        callback(new Error('请输入角色名称'))
      } else {
        callback()
      }
    }
    const validateIsenable = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择是否启用'))
      } else {
        callback()
      }
    }
    // 添加和编辑权限结束
    // 添加和编辑栏目开始
    const validatePowerPid = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择栏目'))
      } else {
        callback()
      }
    }
    const validatePowerName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    const validatePowerControl = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入Thinkphp控制器'))
      } else {
        callback()
      }
    }
    const validatePowerAction = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入Thinkphp控制器方法'))
      } else {
        callback()
      }
    }
    const validatePowerAccess = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入vue控制路由权限'))
      } else {
        callback()
      }
    }
    const validatePowerSort = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入排序'))
      } else {
        callback()
      }
    }
    const validatePowerIsshow = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择是否显示'))
      } else {
        callback()
      }
    }
    // 添加和编辑栏目结束
    return {
      // 默认开启加载
      spinShow: true,
      // 默认提交状态
      formSave: false,
      // 添加还是编辑
      formType: this.data.type,
      // 添加/编辑权限开始
      formCustom: {
        name: '',
        isenable: '',
        powerid: [],
        id: this.data.id
      },
      // 其他数据
      name_e: false,
      isenablelist: [],
      ruleCustom: {
        name: [
          {validator: validateName, trigger: 'change'},
          {min: 2, message: '请输入2-10数字字母组合'},
          {max: 10, message: '请输入2-10数字字母组合'}
        ],
        isenable: [
          {validator: validateIsenable, trigger: 'change'}
        ]
      },
      // 添加/编辑栏目信息
      // 全选数据
      powerData: [],
      indeterminate: false,
      checkAll: false,
      Arrid: [],
      // 菜单参数
      powerTitle: true,
      powerModel: false,
      // 添加还是编辑
      formPowerType: 'add',
      isshowlist: [],
      poweridlist: [],
      // 添加和编辑开始
      formCustomPower: {
        id: '',
        pid: '',
        name: '',
        control: '',
        action: '',
        access: '',
        sort: '0',
        isshow: ''
      },
      ruleCustomPower: {
        pid: [
          {validator: validatePowerPid, trigger: 'change'}
        ],
        name: [
          {validator: validatePowerName, trigger: 'change'},
          {max: 10, message: '最大输入10个字符', trigger: 'change'}
        ],
        control: [
          {validator: validatePowerControl, trigger: 'change'},
          {
            type: 'string',
            pattern: /^[a-z0-9A-Z_]+$/,
            message: '输入的Thinkphp控制器必须字母数字下划线之间组合',
            trigger: 'change'
          }
        ],
        action: [
          {validator: validatePowerAction, trigger: 'change'},
          {
            type: 'string',
            pattern: /^[a-z0-9A-Z_]+$/,
            message: '输入的Thinkphp控制器方法必须字母数字下划线之间组合',
            trigger: 'change'
          }
        ],
        access: [
          {validator: validatePowerAccess, trigger: 'change'},
          {
            type: 'string',
            pattern: /^[a-z0-9A-Z_]+$/,
            message: '输入的vue控制路由权限必须字母数字下划线之间组合',
            trigger: 'change'
          }
        ],
        sort: [
          {validator: validatePowerSort, trigger: 'change'},
          {
            pattern: /^[0-9]+$/, // 正则表达式验证
            message: '只能输入数字',
            trigger: 'change'
          }
        ],
        icon: [
          {max: 20, message: '最多输入20个字符', trigger: 'change'},
          {
            type: 'string',
            pattern: /^[a-z0-9A-Z-_]+$/,
            message: '输入的组件必须字母数字_之间组合',
            trigger: 'change'
          }
        ],
        isshow: [
          {validator: validatePowerIsshow, trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    // 信息保存
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 防止多次提交
          this.formSave = true
          // 请求数据保存
          this.$api.role(this.formCustom, this.formType).then((response) => {
            if (response.code === 200) {
              bus.$emit('loadList', this.formType)
              this.$Message.success(response.msg)
              this.$emit('toggle', {type: 'list'})
            } else {
              this.$Message.error(response.msg)
            }
            this.formSave = false
          }).catch((error) => {
            this.formSave = false
            this.$Message.error(error.message)
          })
        }
      })
    },
    // 清楚表单
    handleReset (name) {
      this.checkAll = false
      this.formCustom.powerid = []
      this.$refs[name].resetFields()
    },
    // 信息获取
    getInfoData (id) {
      // 获取初始化信息
      this.$api.role({id: id}, this.formType, 'get').then((response) => {
        if (response.code === 200) {
          if (response.data.role) {
            this.formType = 'edit'
            if (window.localStorage.getItem('id') !== '1') {
              this.name_e = true
            }
            this.formCustom.id = response.data.role.id
            this.formCustom.name = response.data.role.name
            this.formCustom.isenable = response.data.role.isenable
            this.formCustom.powerid = response.data.powerid
            this.indeterminate = true
          }
          // 初始化绑定数据
          this.isenablelist = response.data.isenablelist
          this.powerData = response.data.list
          this.Arrid = response.data.arrid
          this.spinShow = false
        } else {
          this.$Message.error(response.msg)
          this.$emit('toggle', {type: 'list'})
        }
      }).catch((error) => {
        this.$Message.error(error.message)
        this.spinShow = false
      })
    },
    // 权限全选选择和取消
    handleCheckAll () {
      if (this.indeterminate) {
        this.checkAll = false
      } else {
        this.checkAll = !this.checkAll
      }
      this.indeterminate = false

      if (this.checkAll) {
        this.formCustom.powerid = this.Arrid
      } else {
        this.formCustom.powerid = []
      }
    },
    // 权限选择关联全选和取消
    checkAllGroupChange (data) {
      if (data.length > 0) {
        this.indeterminate = true
        this.checkAll = false
      } else {
        this.indeterminate = false
        this.checkAll = false
      }
    },
    // 获取栏目
    getRolePower (id) {
      // 重置表单
      this.$refs['formCustomPower'].resetFields()
      // 获取初始化信息
      this.$api.role({id: id, type: 'power'}, id ? 'edit' : 'add', 'get').then((response) => {
        if (response.code === 200) {
          if (response.data.row) {
            this.powerTitle = false
            this.formPowerType = 'edit'
            this.formCustomPower = response.data.row
          }
          // 初始化绑定数据
          this.poweridlist = response.data.poweridlist
          this.isshowlist = response.data.isshowlist
          this.powerModel = true
        } else {
          this.$Message.error(response.msg)
        }
      }).catch((error) => {
        this.$Message.error(error.message)
      })
    },
    // 保存栏目
    saveRolePower (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 防止多次提交
          this.formSave = true
          // 初始化保存类型
          this.formCustomPower.type = 'power'
          // 请求数据保存
          this.$api.role(this.formCustomPower, this.formPowerType).then((response) => {
            if (response.code === 200) {
              this.getInfoData(this.formCustom.id)
              this.$Message.success(response.msg)
              this.powerModel = false
            } else {
              this.$Message.error(response.msg)
            }
            this.formSave = false
          }).catch((error) => {
            this.formSave = false
            this.$Message.error(error.message)
          })
        }
      })
    },
    // 删除栏目
    delRolePower (row) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '<p>你要定要删除该信息吗? </p>',
        loading: true,
        width: 240,
        onOk: () => {
          setTimeout(() => {
            // 读取请求数据
            this.$api.role({
              id: row.id,
              type: 'power',
              name: row.name // 删除日记记录信息标注
            }, 'del', 'delete').then((response) => {
              if (response.code === 200) {
                this.getInfoData(this.formCustom.id)
                this.$Message.success(response.msg)
              } else {
                this.$Message.error(response.msg)
              }
            }).catch((error) => {
              this.$Message.error(error.message)
            })
            this.$Modal.remove()
          }, 1000)
        }
      })
    }
  },
  created () {
    // 获取信息
    this.getInfoData(this.formCustom.id)
  }
}
</script>
